/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * listSetorEmpresa.java
 *
 * Created on 30/11/2011, 09:48:29
 */
package visao;

import fachada.FachadaBDR;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import setorEmpresa.SetorEmpresa;
import util.ErroAcessoRepositorioException;
import util.KeyValue;
import util.Util;

/**
 *
 * @author Administrador
 */
public class listSetorEmpresa extends javax.swing.JFrame {

    public String[] titulos = new String[]{"#", "Descrição", "Empresa", "Centro de Custo", "Status"};
    public DefaultTableModel defTable;
    public CadSetorEmpresa cadastroSetorEmpresa = new CadSetorEmpresa();

    /** Creates new form listSubSetor */
    public listSetorEmpresa() {

        /** Creates new form listSetorEmpresa */
        try {
            FachadaBDR objfaFachadaBDR = FachadaBDR.getInstancia();
            List<SetorEmpresa> listSetorEmpresa = objfaFachadaBDR.listarSetorEmpresa(" AND status_setor_empresa = true ");

            // Setando a tabela
            this.defTable = atualizaLista(listSetorEmpresa);
        } catch (ErroAcessoRepositorioException ex) {
            System.out.println(ex.getMessage());
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }

        initComponents();
        this.setLocationRelativeTo(null);
        this.setIconImage(new ImageIcon(getClass().getResource("/Imagens/SetorEmpresa.gif")).getImage());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton_Cadastrar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel_Mensagem = new javax.swing.JLabel();
        jButton_Atualizar = new javax.swing.JButton();
        jButton_Remover = new javax.swing.JButton();
        jButton_Editar = new javax.swing.JButton();
        jLabel_DescricaoEmpresa = new javax.swing.JLabel();
        jTextField_Buscar = new javax.swing.JTextField();
        jButton_Buscar = new javax.swing.JButton();

        setTitle("Setor Empresa");
        setResizable(false);

        jButton_Cadastrar.setText("Cadastrar");
        jButton_Cadastrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_CadastrarActionPerformed(evt);
            }
        });

        jTable1.setModel(this.defTable);
        jScrollPane1.setViewportView(jTable1);

        jButton_Atualizar.setText("Atualizar");
        jButton_Atualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_AtualizarActionPerformed(evt);
            }
        });

        jButton_Remover.setText("Remover");
        jButton_Remover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_RemoverActionPerformed(evt);
            }
        });

        jButton_Editar.setText("Editar");
        jButton_Editar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_EditarActionPerformed(evt);
            }
        });

        jLabel_DescricaoEmpresa.setText("Setor Empresa:");

        jTextField_Buscar.setText("");
        jTextField_Buscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField_BuscarActionPerformed(evt);
            }
        });

        jButton_Buscar.setText("Buscar");
        jButton_Buscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_BuscarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel_Mensagem, javax.swing.GroupLayout.DEFAULT_SIZE, 655, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton_Cadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton_Editar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton_Atualizar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(16, 16, 16)
                        .addComponent(jButton_Remover, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(28, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 686, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(jLabel_DescricaoEmpresa)
                .addGap(18, 18, 18)
                .addComponent(jTextField_Buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(26, 26, 26)
                .addComponent(jButton_Buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(375, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel_DescricaoEmpresa)
                    .addComponent(jTextField_Buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton_Buscar))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 358, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton_Editar)
                    .addComponent(jButton_Remover)
                    .addComponent(jButton_Cadastrar)
                    .addComponent(jButton_Atualizar))
                .addGap(18, 18, 18)
                .addComponent(jLabel_Mensagem, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(28, 28, 28))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton_CadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_CadastrarActionPerformed
        // TODO add your handling code here:


        try {
            if (!this.cadastroSetorEmpresa.isVisible()) {
                this.cadastroSetorEmpresa = new CadSetorEmpresa();
                this.cadastroSetorEmpresa.setVisible(true);
            }

            FachadaBDR objfaFachadaBDR = FachadaBDR.getInstancia();
            List<SetorEmpresa> listSetorEmpresa = objfaFachadaBDR.listarSetorEmpresa(" AND status_setor_empresa = true ");

            // Setando a tabela
            this.defTable = atualizaLista(listSetorEmpresa);

            // Setando a nova listagem
            jTable1.setModel(this.defTable);

            jTable1.revalidate();

        } catch (Exception ex) {
            jLabel_Mensagem.setText(ex.getMessage());
        }




    }//GEN-LAST:event_jButton_CadastrarActionPerformed

    private void jButton_AtualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_AtualizarActionPerformed
        // TODO add your handling code here:

        try {
            // instanciando a fachada
            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();

            // Listando os cargos
            List<SetorEmpresa> listSetorEmpresa = objFachadaBDR.listarSetorEmpresa(" AND status_setor_empresa = true ");

            // Setando a tabela
            this.defTable = atualizaLista(listSetorEmpresa);

            // Setando a nova listagem
            jTable1.setModel(this.defTable);

            jTable1.revalidate();
        } catch (Exception ex) {
            jLabel_Mensagem.setText(ex.getMessage());
        }

    }//GEN-LAST:event_jButton_AtualizarActionPerformed

    private void jButton_RemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_RemoverActionPerformed
        // TODO add your handling code here:

        int cancelar = JOptionPane.showConfirmDialog(null, "Deseja Remover este Setor Empresa?");
        if (cancelar == JOptionPane.YES_OPTION) {
            try {
                // pegando a linha selecionada
                if (this.jTable1.getSelectedColumnCount() == 0 || this.jTable1.getSelectedColumnCount() > 1) {
                    throw new Exception("Favor selecionar um Setor Empresa");
                }

                int linha = this.jTable1.getSelectedRow();

                // recuperando o Cpf do funcionario
                int idSetorEmpresa = (Integer) this.jTable1.getValueAt(linha, 0);

                // instanciando a fachada
                FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();

                objFachadaBDR.removerSetorEmpresa(idSetorEmpresa);

                // Listando as Empresas
                List<SetorEmpresa> listSetorEmpresa = objFachadaBDR.listarSetorEmpresa(" AND status_setor_empresa = true ");

                // Setando a tabela
                this.defTable = atualizaLista(listSetorEmpresa);

                // Setando a nova listagem
                jTable1.setModel(this.defTable);

                jTable1.revalidate();

                jLabel_Mensagem.setText("Removido com sucesso!");

            } catch (Exception ex) {
                jLabel_Mensagem.setText(ex.getMessage());
            }
        }


    }//GEN-LAST:event_jButton_RemoverActionPerformed

    private void jButton_EditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_EditarActionPerformed
        // TODO add your handling code here:
        try {
            // pegando a linha selecionada
            if (this.jTable1.getSelectedColumnCount() == 0) {
                throw new Exception("Favor selecionar um Setor Empresa");
            }

            // Pegando a linha que está selecionada
            int linha = this.jTable1.getSelectedRow();

            int idSetorEmpresa = (Integer) this.jTable1.getValueAt(linha, 0);

            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();

            SetorEmpresa objSetorEmpresa = objFachadaBDR.procurarSetorEmpresa(idSetorEmpresa);


            // se a tela da Empresa ja estiver instanciada
            if (!this.cadastroSetorEmpresa.isVisible()) {
                this.cadastroSetorEmpresa = new CadSetorEmpresa(objSetorEmpresa.getIdSetorEmpresa());
                this.cadastroSetorEmpresa.setVisible(true);
            }
            // Listando as Empresas
            List<SetorEmpresa> listSetorEmpresa = objFachadaBDR.listarSetorEmpresa(" AND status_setor_empresa = true ");

            // Setando a tabela
            this.defTable = atualizaLista(listSetorEmpresa);

            // Setando a nova listagem
            jTable1.setModel(this.defTable);

            // atualizando as Empresas
            jTable1.revalidate();

        } catch (Exception ex) {
            jLabel_Mensagem.setText(ex.getMessage());
        }

    }//GEN-LAST:event_jButton_EditarActionPerformed

    private void jButton_BuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_BuscarActionPerformed
        // TODO add your handling code here:

        try {
            // instanciando a fachada
            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();
            String strSetorEmpresa = jTextField_Buscar.getText().trim();
            
            // Listando as Empresas
            List<SetorEmpresa> listSetorEmpresa = objFachadaBDR.listarSetorEmpresaPorDescricao(strSetorEmpresa);

            // Setando a tabela
            this.defTable = atualizaLista(listSetorEmpresa);

            // Setando a nova listagem
            jTable1.setModel(this.defTable);
            jTable1.revalidate();

        } catch (Exception ex) {
            jLabel_Mensagem.setText(ex.getMessage());
        }

    }//GEN-LAST:event_jButton_BuscarActionPerformed

    private void jTextField_BuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField_BuscarActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField_BuscarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(listSetorEmpresa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(listSetorEmpresa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(listSetorEmpresa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(listSetorEmpresa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new listSetorEmpresa().setVisible(true);
            }
        });
    }

    public DefaultTableModel atualizaLista(List<SetorEmpresa> listSetorEmpresa) {
        //{"#", "Descrição Sub Setor", "Setor", "QTD Maxima", "QTD Minima", "QTD Atual", "Status"}
        // Criando o objeto 
        Object[][] resposta = new Object[listSetorEmpresa.size()][5];

        for (int i = 0; i < resposta.length; i++) {

            SetorEmpresa objSetorEmpresa = listSetorEmpresa.get(i);

            resposta[i][0] = objSetorEmpresa.getIdSetorEmpresa();
            resposta[i][1] = objSetorEmpresa.getDescricaoSetor();
            resposta[i][2] = objSetorEmpresa.getEmpresa().getDescricaoEmpresa();
            resposta[i][3] = objSetorEmpresa.getCentroCusto();
            resposta[i][4] = objSetorEmpresa.getStatusSetorEmpresa() ? "Ativo" : "Inativo";

        }

        // Setando a tabela
        return new DefaultTableModel(resposta, titulos);

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton_Atualizar;
    private javax.swing.JButton jButton_Buscar;
    private javax.swing.JButton jButton_Cadastrar;
    private javax.swing.JButton jButton_Editar;
    private javax.swing.JButton jButton_Remover;
    private javax.swing.JLabel jLabel_DescricaoEmpresa;
    private javax.swing.JLabel jLabel_Mensagem;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField_Buscar;
    // End of variables declaration//GEN-END:variables
}
